package com.deep.transaction.demo.service.impl;


import com.deep.transaction.demo.dao.UserMapper;
import com.deep.transaction.demo.entity.User;
import com.deep.transaction.demo.service.OtherService;
import com.deep.transaction.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service("demoUserService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OtherService otherService;

    // 在同一个事务内，会回滚
    @Transactional(propagation = Propagation.REQUIRED)
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
//    @Transactional(propagation = Propagation.NESTED)
    // 不会因为子事务异常，回滚
//    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public void save() {
        User user = new User("服部半藏");
        userMapper.insertSelective(user);

        System.out.println("out done");
        try {
            otherService.method1();
        } catch (Exception e) {
            log.error("otherService.method1 e = ", e);
        }

    }

    @Transactional(propagation = Propagation.REQUIRED, timeout = 1)
    @Override
    public void saveTimeout() throws InterruptedException {
        User user = new User("服部半藏");
        userMapper.insertSelective(user);

        System.out.println("out done");

        TimeUnit.SECONDS.sleep(3);
//        try {
//            TimeUnit.SECONDS.sleep(3);
////            otherService.method1();
//        } catch (Exception e) {
//            log.error("otherService.method1 e = ", e);
//        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void method1() {
        User user = new User("宫本武藏");
        userMapper.insertSelective(user);
    }


}